package Graphique;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.util.Timer;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Metier.*;

public class Fenetre extends JFrame implements KeyListener{
	
	private static final long serialVersionUID = 1L;

	private RotatingImage BIvoiture;
	
	private JLabel l_voiture;
	
	// Units : milliseconds
	private static int time = 10;
	
	private SimMap map;
	
	
	public Voiture voiture;
	
	public Fenetre() throws InterruptedException {
		super();
		

		map = new SimMap(1000, 1000);
		
		JPanel p_principal = new JPanel();
		this.addKeyListener(this);
		

		voiture = new Voiture(50,50,90.0,0, map);

		
		try {
			BIvoiture = new RotatingImage(ImageIO.read(new File("src\\Graphique\\triangle.png")));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		l_voiture = new JLabel(new ImageIcon(BIvoiture));
		
		p_principal.setLayout(null);
		p_principal.setBackground(Color.white);
		p_principal.add(l_voiture);

		this.setSize(new Dimension(map.getWidth(),map.getHeight()));
		this.setContentPane(p_principal);
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		placerVoiture();
		
		Timer t = new Timer();
		MyTimerTask task = new MyTimerTask(this);
		t.scheduleAtFixedRate(task, 0, time);
	}
	
	
	public void keyTyped(KeyEvent e) {}
	
	
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_UP) {
			voiture.setVitesse(voiture.getVitesse()-5);
		}
		else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
			voiture.setVitesse(voiture.getVitesse()+5);
		}
		else if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
			voiture.setDirection(voiture.getDirection()+ 10.0);
		}
		else if(e.getKeyCode() == KeyEvent.VK_LEFT) {
			voiture.setDirection(voiture.getDirection()-10.0);
		}
		
	}
	
	
	public void keyReleased(KeyEvent e) {}

	public void placerVoiture() {
		Insets insets = this.getContentPane().getInsets();
		Dimension size = l_voiture.getPreferredSize();
		
		voiture.bouger(time);
		
		BIvoiture.setAngle((voiture.getDirection() / 180) * Math.PI);
		
		l_voiture.setBounds(voiture.getPositionX() / map.getScale() + insets.left, voiture.getPositionY() / map.getScale() + insets.top, size.width, size.height);
	}
	
	public static void main (String[] args) throws InterruptedException {
		new Fenetre();
	}
	
	
}
